package com.jlb.demo.service;

import com.jlb.demo.entity.Order;
import com.jlb.demo.entity.User;
import com.jlb.demo.exception.BusinessException;
import com.jlb.demo.payment.Payment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单服务类 - 演示异常处理和业务逻辑
 */
public class OrderService {
    
    // 模拟数据库存储
    private Map<Long, Order> orderMap = new HashMap<>();
    private Map<Long, User> userMap = new HashMap<>();
    
    /**
     * 创建订单
     * @param userId 用户ID
     * @param amount 订单金额
     * @param description 订单描述
     * @return 创建的订单
     * @throws BusinessException 当用户不存在时抛出异常
     */
    public Order createOrder(Long userId, Double amount, String description) {
        // 检查用户是否存在
        User user = userMap.get(userId);
        if (user == null) {
            throw new BusinessException(
                BusinessException.ErrorCode.USER_NOT_FOUND,
                "用户不存在，ID：" + userId
            );
        }
        
        // 检查用户是否成年
        if (!user.isAdult()) {
            throw new BusinessException(
                BusinessException.ErrorCode.INVALID_PARAMETER,
                "未成年用户不能下单，用户ID：" + userId
            );
        }
        
        // 生成订单ID
        Long orderId = System.currentTimeMillis();
        
        // 创建订单
        Order order = new Order(orderId, userId, amount, description);
        orderMap.put(orderId, order);
        
        System.out.println("✅ 订单创建成功：" + order.getSummary());
        return order;
    }
    
    /**
     * 支付订单 - 演示多态
     * @param orderId 订单ID
     * @param payment 支付方式（多态）
     * @return 是否支付成功
     * @throws BusinessException 当订单不存在或状态不正确时抛出异常
     */
    public boolean payOrder(Long orderId, Payment payment) {
        // 获取订单
        Order order = orderMap.get(orderId);
        if (order == null) {
            throw new BusinessException(
                BusinessException.ErrorCode.ORDER_NOT_FOUND,
                "订单不存在，ID：" + orderId
            );
        }
        
        // 检查订单状态
        if (!"待支付".equals(order.getStatus())) {
            throw new BusinessException(
                BusinessException.ErrorCode.ORDER_ALREADY_PAID,
                "订单状态不正确，当前状态：" + order.getStatus()
            );
        }
        
        // 获取用户信息
        User user = userMap.get(order.getUserId());
        if (user == null) {
            throw new BusinessException(
                BusinessException.ErrorCode.USER_NOT_FOUND,
                "用户不存在，ID：" + order.getUserId()
            );
        }
        
        // 计算折扣金额（VIP用户打9折）
        Double finalAmount = order.calculateDiscountedAmount(user.getIsVip());
        
        System.out.println("=== 订单支付处理 ===");
        System.out.println("订单ID: " + orderId);
        System.out.println("原金额: " + order.getAmount() + " 元");
        System.out.println("用户VIP: " + (user.getIsVip() ? "是" : "否"));
        System.out.println("折扣后金额: " + finalAmount + " 元");
        System.out.println("支付方式: " + payment.getPaymentMethod());
        
        // 调用支付接口（多态）
        boolean paymentSuccess = payment.pay(orderId, finalAmount);
        
        if (paymentSuccess) {
            // 支付成功，更新订单状态
            order.pay(payment.getPaymentMethod());
            
            // 如果用户余额充足，从余额扣除
            if (user.getBalance() >= finalAmount) {
                user.consume(finalAmount);
            }
        }
        
        return paymentSuccess;
    }
    
    /**
     * 取消订单
     * @param orderId 订单ID
     * @throws BusinessException 当订单不存在时抛出异常
     */
    public void cancelOrder(Long orderId) {
        Order order = orderMap.get(orderId);
        if (order == null) {
            throw new BusinessException(
                BusinessException.ErrorCode.ORDER_NOT_FOUND,
                "订单不存在，ID：" + orderId
            );
        }
        
        order.cancel();
    }
    
    /**
     * 获取用户的所有订单
     * @param userId 用户ID
     * @return 订单列表
     */
    public List<Order> getUserOrders(Long userId) {
        List<Order> userOrders = new ArrayList<>();
        for (Order order : orderMap.values()) {
            if (userId.equals(order.getUserId())) {
                userOrders.add(order);
            }
        }
        return userOrders;
    }
    
    /**
     * 获取所有订单
     * @return 订单列表
     */
    public List<Order> getAllOrders() {
        return new ArrayList<>(orderMap.values());
    }
    
    /**
     * 添加用户（用于测试）
     * @param user 用户
     */
    public void addUser(User user) {
        userMap.put(user.getId(), user);
    }
    
    /**
     * 获取用户（用于测试）
     * @param userId 用户ID
     * @return 用户
     */
    public User getUser(Long userId) {
        return userMap.get(userId);
    }
} 